#ifndef _LIBTIMERS_H_
#define _LIBTIMERS_H_
#include <stdint.h>
#include <stdlib.h>
#include <assert.h>
#include <sys/time.h>

#if defined(__cplusplus)                                                                               
extern "C" {                                                                                           
#endif 

/* you can specify time function, like the default get_now_time_ms().
 However you should notice it MUST BE ascending function as time passes */
typedef uint64_t (*GET_TIME_FUNC)(void);


typedef struct LT_TIMERPOOL LT_TIMERPOOL;


/* event structure */
typedef struct {
    uint32_t timer_id;
    void *data;
} LT_TIMER_EVENT;


/* default time function,
   get UNIX time with 1ms granularity by gettimeofday() */
uint64_t get_now_time_ms();

/* allocate and initialize a timer pool object.
   'func' can be NULL, so the get_now_time_ms() will be used */
LT_TIMERPOOL *lt_new(GET_TIME_FUNC func);

/* free a timer pool object */
void lt_destroy(LT_TIMERPOOL *pool);

/* get a timer descriptor, like fd in unix */
uint32_t lt_timer_open(LT_TIMERPOOL *pool);
/* return a timer descriptor to pool manager.
   also remove it if it is still in time queue.
  return 0 for success, -1 if failed */
int lt_timer_close(LT_TIMERPOOL *pool, uint32_t timer_id);


/* set a timer with opened descriptor, 
   data can be any kind of data with a size of pointor,
   it will be returned when timer triggered.
   'interval' is how long it will happened from now.
  return 0 for success, -1 if failed */
int lt_set_timer(LT_TIMERPOOL *pool, uint32_t timer_id, void *data, uint32_t interval);


/* cancel a timer before it times up 
  return 0 for success, -1 if failed */
int lt_cancel_timer(LT_TIMERPOOL *pool, uint32_t timer_id);


/* get the time-up timer events.
   The timer_id and its data are stored in 'events'.
   'events' are allocated internally and must be freed by lt_free_events */
int lt_poll(LT_TIMERPOOL *pool, LT_TIMER_EVENT **events);

/* free the events array allocated by 'lt_poll' */
void lt_free_events(LT_TIMERPOOL *pool, LT_TIMER_EVENT *events);


/* get the number of timers that still in time queue */
int lt_timer_size(LT_TIMERPOOL *pool);


#if defined(__cplusplus)
}
#endif

#endif


